import elemengUI from 'element-ui'

export default{
  data: {},
  addConnection (connection) {
    const connections = this.getConnections()
    const key = this.getConnectionKey(connection)
    if (connections[key]) {
      elemengUI.Message({
        type: 'error',
        message: window.$Vue.$t('ConnectionPrompt.ConnectionAlreadyExists')
      })
      return false
    }
    connections[key] = connection
    this.setConnection(connections)
    return true
  },
  getConnections (returnList = false) {
    let connections = localStorage.connections || '{}'
    connections = JSON.parse(connections)
    connections = this.sortByKey(connections)
    if (returnList) {
      connections = Object.keys(connections).map(key => connections[key])
    }
    return connections
  },
  delConnection(item){
    var servers=this.getConnections (false);
    delete servers[this.getConnectionKey(item)]
    this.setConnection(servers)
  },
  getConnectionKey (connection) {
    return connection.Host +":"+ connection.Port +":"+ connection.Name
  },
  setConnection (connections) {
    localStorage.connections = JSON.stringify(connections)
  },
  sortByKey (obj) {
    return Object.keys(obj).sort()
      .reduce((acc, c) => { acc[c] = obj[c]; return acc }, {})
  },
  set (name, value) {
    this.data[name] = value
  },
  get (name) {
    return this.data[name]
  },
  setLang(lang){
    localStorage.lang = lang
  },
  getLang(){
    return localStorage.lang
  }
}
